package cn.sc.allinpay.allfavour.base.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * 数据库
 *
 * @author panyi
 */
public class DbHelper extends OrmLiteSqliteOpenHelper {

    /**
     * 数据库版本
     */
    private static int dbVersion = 1;
    /**
     * 数据库名称
     */
    private static String dbName;
    /**
     * 需要创建表的class类
     */
    private static String[] clss;

    /**
     * 上下文
     */
    private static Context context = null;

    private DbHelper() {
        super(context, dbName, null, dbVersion);
    }

    private static class SingleDbHelper {
        private static final DbHelper INSTANCE = new DbHelper();
    }

    public static final DbHelper getInstance() {
        return SingleDbHelper.INSTANCE;
    }

    /**
     * 初始化
     *
     * @param context_   上下文
     * @param dbVersion_ 数据库版本
     * @param dbName_    数据库名称
     * @param clsNames   数据表class
     */
    public static void initialize(Context context_, int dbVersion_, String dbName_, String... clsNames) {
        dbVersion = dbVersion_;
        dbName = dbName_;
        context = context_;
        clss = clsNames;
    }

    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource) {
        // TODO Auto-generated method stub
        if (clss != null && clss.length > 0) {
            try {
                for (int i = 0; i < clss.length; i++) {
                    TableUtils.createTable(connectionSource,
                            Class.forName(clss[i]));
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                clss = null;
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        if (clss != null && clss.length > 0) {
            try {
                for (int i = 0; i < clss.length; i++) {
                    TableUtils.dropTable(connectionSource,
                            Class.forName(clss[i]), true);
                }
                onCreate(database, connectionSource);
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
